<template xmlns:background-color="http://www.w3.org/1999/xhtml">
  <a-modal
    :title="title"
    :width="1200"
    :visible="true"
    v-if="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-row :gutter="10">
      <a-col :md="12" :sm="24">
        <a-card :bordered="false">
          <!-- 按钮操作区域 -->
          <a-row style="margin-left: 14px">
          </a-row>
          <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
            <!-- 区域树-->
            <a-col :md="10" :sm="24">
              <template>
                <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
               <span style="user-select: none">
            <a-tree
              checkable
              v-model="checkedKeys"
              @select="onSelect"
              :selected-keys="selectedKeys"
              :treeData="areaTree"
              :expanded-keys="iExpandedKeys"
              :auto-expand-parent="autoExpandParent"
              :load-data="onLoadData"
              @check="onCheck"
              @expand="onExpand">
              <template #title="item">
                 <!-- 项目黑色，区域蓝色，楼栋红色，单元紫色，楼层绿色，设备橙色                   -->
                 <a-icon v-if="item.isArea==6" slot="branches" type="branches"/>
                    <span v-if="item.isArea==1" style="color:blue">{{ item.title }}</span>
                    <span v-if="item.isArea==2" style="color:red">{{ item.title }}</span>
                    <span v-if="item.isArea==3" style="color:purple">{{ item.title }}</span>
                    <span v-if="item.isArea==4" style="color:green">{{ item.title }}</span>
                    <span v-if="item.isArea==0" style="color:black">{{ item.title }}</span>
                    <span v-if="item.isArea==5" style="color:orange">{{ item.title }}</span>
                    <span v-if="item.isArea==6" style="color:royalblue">{{ item.title }}</span>
              </template>
             </a-tree>
                </span>
                </a-dropdown>
              </template>
            </a-col>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import {deleteAction, getAction, httpAction, postAction} from '@/api/manage'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
// 表头
const columns = [
  {
    title: '机构名称',
    dataIndex: 'departName'
  },
  {
    title: '机构类型',
    align: 'center',
    dataIndex: 'orgType'
  },
  {
    title: '机构编码',
    dataIndex: 'orgCode',
  },
  {
    title: '手机号',
    dataIndex: 'mobile'
  },
  {
    title: '传真',
    dataIndex: 'fax'
  },
  {
    title: '地址',
    dataIndex: 'address'
  },
  {
    title: '排序',
    align: 'center',
    dataIndex: 'departOrder'
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    scopedSlots: {customRender: 'action'}
  }
]
export default {
  name: 'areaTree',
  mixins: [JeecgListMixin],
  components: {
    // SelectProjectModal,
    // AreaModal,
    // AddModalForm,
  },
  data() {
    return {
      before: [],
      confirmLoading: false,
      checkedKeys: [],
      iExpandedKeys: [],
      isProject: false,
      isArea: false,
      isBuild: false,
      isUnit: false,
      isFloor: false,
      loading: false,
      buildingId: "",
      areaId: "",
      projectId: "",
      unitId: "",
      floorId: "",
      userId: "",
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      visible: false,
      areaTree: [],
      rightClickNode: {},
      model: {},
      dropTrigger: '',
      depart: {},
      columns: columns,
      disableSubmit: false,
      currentProjectId: '',
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      form: this.$form.createForm(this),
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      validatorRules: {
        name: {rules: [{required: true, message: '请输入区域名称!'}]},

      },
      title: '门禁授权',
      url: {
        deleteArea: '/area/delete',
        deleteBuild: 'building/delete',
        deleteUnit: 'unit/delete',
        deleteFloor: 'floor/delete',
        edit: '/area/updateById',
        deleteBatch: '/area/deleteBatch',
        exportXlsUrl: "area/exportXls",
        importExcelUrl: "area/importExcel",
        getBindedDevice: "/user/user/getBindedDevice",
        createSingleUser: "/user/user/createSingleUser",
        deleteSingleUser: "/user/user/deleteSingleUser",
        getAreatreeById: "/project/getAreaTreeById",
        getBindDevice: "/device/getBindDevice",
        getAreaChildren: '/project/getChildren',
        getBuildChildren: '/area/getChildren',
        getUnitChildren: '/building/getChildren',
        getFloorChildren: '/unit/getChildren',
        getHouseChildren: '/floor/getChildren',
        createOrDelete: '/user/user/createOrDelete'
      },
      rightClickSelect: {},
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    loadData() {
      this.areaTree = []
      this.refresh();
    },
    finish() {

    },

    close() {
      this.$emit('close');
      this.areaTree = [];
      this.treeNode=[];
      this.checkedKeys=[];
       this.iExpandedKeys=[];
        this.visible = false;
    },
    showIt(id, projectId) {
      this.visible = true;
      console.log(id);
      this.userId = id;
      this.loadTree(projectId)
      this.getBindedDevice(id);
    },
    getBindedDevice(id) {
      getAction(this.url.getBindedDevice, {userId: id}).then(
        (res) => {
          if (res.success) {
            for (let sn of res.result) {
              this.checkedKeys.push(sn)
            }
            this.before = this.checkedKeys;
              console.log("checked"+this.checkedKeys)

            console.log(this.iExpandedKeys)
          }
        }
      )
    },

    handleOk() {
      const that = this;
      //用户选择之前的设备
      let before = this.before;
      //用户当前选择的设备
      let current = that.checkedKeys;
      console.log("之前选中的", before)
      console.log("当前选中的", current)
      //用户取消的设备
      let miss = [];
      //用户新增的设备
      let more = [];
      miss = before.filter((i) => {
        return current.indexOf(i) < 0
      })
      more = current.filter((i) => {
        return before.indexOf(i) < 0
      })

      let miss1 = ""
      miss.forEach((item) => {
        let node = []
        this.getTreeNode(that.areaTree, [item], node)
        if (node.length !== 0 && node[0].isArea === 6) {
          miss1 = miss1 + "," + item
        }
      })
      miss1 = miss1.substring(1, miss1.length );
      let more1 = ""
      more.forEach((item) => {
        let node = []
        this.getTreeNode(that.areaTree, [item], node)
        if (node.length !== 0 && node[0].isArea === 6) {
            more1 = more1 + "," + item
        }
      })
      more1 = more1.substring(1, more1.length );

      let params ={};
      params.userId=this.userId;
      params.removeDeviceStr=miss1;
      params.insertDeviceStr=more1;
      postAction(this.url.createOrDelete, params).then(
        (res) => {
          if (res.success) {
            this.$message.success("发送成功，待生效")
          } else {
            this.$message.warning(res.message)
          }
        }
      )

      this.visible = false;
      this.areaTree = [];
      this.checkedKeys=[];
    },
    loadTree(projectId) {
      var that = this
      that.areaTree = []
      getAction(this.url.getAreatreeById, {id: projectId}).then((res) => {
        if (res.success) {
          if (res.result !== null) {
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.areaTree.push(temp)
            }
          }
        }
        this.loading = false
      })
      console.log("@@@", that.areaTree)
    },
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        setTimeout(async () => {
          if (treeNode.dataRef.isArea != null && treeNode.dataRef.isArea !== 6) {
            let param = {}
            let childUrl = ''
            if (treeNode.dataRef.isArea === 1) {
              param.areaId = treeNode.dataRef.key
              childUrl = this.url.getBuildChildren
            }
            if (treeNode.dataRef.isArea === 2) {
              param.buildingId = treeNode.dataRef.key
              childUrl = this.url.getUnitChildren
            }
            if (treeNode.dataRef.isArea === 3) {
              param.unitId = treeNode.dataRef.key
              childUrl = this.url.getFloorChildren
            }
            if (treeNode.dataRef.isArea === 4) {
              param.floorId = treeNode.dataRef.key
              childUrl = this.url.getHouseChildren
            }
            if (treeNode.dataRef.isArea === 5) {
              param.houseId = treeNode.dataRef.key
            }
            /*标识区域*/
            if (treeNode.dataRef.isArea === 0) {
              childUrl = this.url.getAreaChildren
            }
            if (treeNode.dataRef.isArea !== 5) {
              await getAction(childUrl, {id: treeNode.dataRef.key}).then((res) => {
                if (res.success && res.result != null) {
                  treeNode.dataRef.children = res.result
                }
              })
            }
            if (treeNode.dataRef.isArea !== 0) {
              await postAction(this.url.getBindDevice, param).then((res) => {
                if (res.success && res.result != null) {
                  res.result.forEach(item => {
                    item.isArea = 6
                    item.key = item.deviceSn
                    item.leaf = true
                    item.name = item.deviceAlias
                    item.parentId = treeNode.dataRef.key
                    item.title = item.deviceAlias
                    item.value = item.key
                    treeNode.dataRef.children.push(item)
                  })
                }
              })
            }
          }
          this.areaTree = [...this.areaTree];
          resolve();
        }, 100);
      });
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    handleCancel() {
      this.close()
    },
    refresh() {
      this.loading = true
      this.loadTree()
    },
    // 右键操作方法
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      if (node.node.dataRef.isArea === 0) {
        this.resetRight();
        this.isProject = true
      } else if (node.node.dataRef.isArea === 1) {
        this.resetRight();
        this.isArea = true
        this.areaId = node.node.dataRef.id
      } else if (node.node.dataRef.isArea === 2) {
        this.resetRight();
        this.isBuild = true
        this.buildingId = node.node.dataRef.id
      } else if (node.node.dataRef.isArea === 3) {
        this.resetRight();
        this.resetRight();

        this.unitId = node.node.dataRef.id
        this.isUnit = true
      } else if (node.node.dataRef.isArea === 4) {
        this.resetRight();
        this.floorId = node.node.dataRef.id
        this.isFloor = true
      }
      this.rightClickNode = node.node.dataRef
    },
    /*右键删除方法*/
    handleDelete() {
      let that = this
      let url = ''
      if (this.isArea) {
        url = this.url.deleteArea
      } else if (this.isBuild) {
        url = this.url.deleteBuild
      } else if (this.isUnit) {
        url = this.url.deleteUnit
      } else if (this.isFloor) {
        url = this.url.deleteFloor
      }
      deleteAction(url, {id: this.rightClickNode.key}).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadTree()
          that.onClearSelected()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    /*遍历树形集合，并获取到相应id的节点*/
    getTreeNode(areaTree, checkedKeys, checkedNode) {
      if (areaTree.length <= 0 || checkedKeys.length <= 0) {
        return
      }
      for (let i = 0; i < areaTree.length; i++) {
        for (let j = 0; j < checkedKeys.length; j++) {
          if (areaTree[i].key === checkedKeys[j]) {
            if (!checkedNode.includes(areaTree[i])) {
              checkedNode.push(areaTree[i])
            }
          }
        }
        if (areaTree[i].children != null && areaTree[i].children.length != 0) {
          this.getTreeNode(areaTree[i].children, checkedKeys, checkedNode)
        }
      }
    },
    batchDel: function () {
      let that = this
      let checkedNode = []
      this.getTreeNode(this.areaTree, this.checkedKeys, checkedNode)
      console.log("@@@@@@@@@@", checkedNode)
      let delNum = 0
      for (let i = 0; i < checkedNode.length; i++) {
        if (checkedNode[i].isArea != 0) {
          delNum++
        }
      }
      if (delNum <= 0) {
        this.$message.warning('请选择除项目外至少一条记录！')
      } else {
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + delNum + ' 条数据（项目不会删除）?',
          onOk: function () {
            httpAction(that.url.deleteBatch, checkedNode, 'post').then((res) => {
              console.log(res)
              if (res.success) {
                that.$message.success(res.message)
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },

    bindProject() {
      this.$refs.selectProjectModal.setAreaId(this.rightClickNode)
      this.$refs.selectProjectModal.formVisible = true
      this.$refs.selectProjectModal.title = '添加项目区域'
    },
    objectAdd(num) {
      let id = ""
      if (num == 1) {
        this.$refs.addModalForm.title = "新增楼栋"
        id = this.areaId
      } else if (num == 2) {
        this.$refs.addModalForm.title = "新增单元"
        id = this.buildingId
      } else if (num == 3) {
        this.$refs.addModalForm.title = "新增楼层"
        id = this.unitId
      }
      if (id != "" && id != null) {
        this.$refs.addModalForm.setId(id, num)
        this.$refs.addModalForm.disableSubmit = false;
      } else {
        this.$message.warn("请先选择上级")
      }
    },
    resetRight() {
      this.isProject = false
      this.isArea = false
      this.isBuild = false
      this.isUnit = false
      this.isFloor = false
    },
    onCheck(node, e) {

    },
    onExpand(expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键店家下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },

    // onCheck(checkedKeys, info) {
    //   this.checkedKeys = checkedKeys.checked
    // },
    onSelect(selectedKeys, e) {
      let record = e.node.dataRef
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
      this.setValuesToForm(record)
      const that = this;
      //用户选择之前的设备
      let before = that.before;
      //用户当前选择的设备
      let current = that.checkedKeys;
      //用户取消的设备
      let miss = [];
      //用户新增的设备
      let more = [];
      miss = before.filter((i) => {
        return current.indexOf(i) < 0
      })
      more = current.filter((i) => {
        return before.indexOf(i) < 0
      })
      console.log("新增设备为:" + more)
      console.log("删除设备为" + miss)
      console.log("之前选择" + that.before)
      console.log("当前选择为" + that.checkedKeys)
    },
    // 触发onSelect事件时,为区域树右侧的form表单赋值
    setValuesToForm(record) {
      this.form.getFieldDecorator('fax', {initialValue: ''})
      this.form.setFieldsValue(pick(record, 'name', 'sort', 'status', 'remark'))
    },
    onClearSelected() {
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
    },

    // handleAddProject(){
    //   let key = this.currSelected.key
    //   if (!key) {
    //     this.$message.warning('请先选中一个项目!')
    //     return false
    //   }
    //   this.$refs.selectProjectModal.setAreaId(this.currSelected.key)
    //   this.$refs.selectProjectModal.formVisible = true
    //   this.$refs.selectProjectModal.title = '添加项目区域'
    // },

    ok() {

    },
    changeName() {
      this.$refs.areaModal.changeAreaName(this.rightClickNode)
    },

    getFlowGraphData(node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          let temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id
          })
          this.getFlowGraphData(temp)
        }
      }
    },
  },
  created() {
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
  },

}
</script>
<style scoped>
.ant-card-body .table-operator {
  margin: 15px;
}

.anty-form-btn {
  width: 100%;
  text-align: center;
}

.anty-form-btn button {
  margin: 0 5px;
}

.anty-node-layout .ant-layout-header {
  padding-right: 0
}

.header {
  padding: 0 8px;
}

.header button {
  margin: 0 3px
}

.ant-modal-cust-warp {
  height: 100%
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden
}

#app .desktop {
  height: auto !important;
}

/** Button按钮间距 */
.ant-btn {
  margin-left: 3px
}
</style>